package Month11.Day25;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Scanner;

public class Test4 {
    public static void main(String[] args) {
        SAXReader saxReader = new SAXReader();
        Document document = null;
        try {
            document = saxReader.read(new File("D:\\中国玩家\\products.xml"));
            List<Element> list = document.selectNodes("/shop/product");
            Scanner in = new Scanner(System.in);
            System.out.println("请输入商品的编号：");
            int number = in.nextInt();
            System.out.println("请输入购买商品的数量");
            int buyCount = in.nextInt();
            boolean flag = true;

            for (Element e : list) {
                int itemno = Integer.parseInt(e.selectSingleNode("itemno").getText());
                if (number == itemno) {
                    int stockcount = Integer.parseInt(e.selectSingleNode("stockcount").getText());
                    System.out.println("商品编号输入正确，需要购买的商品为：" + e.selectSingleNode("name").getText() +
                            "购买的数量为：" + buyCount);
                    if ((stockcount - buyCount) > 0) {
                        double price = Double.parseDouble(e.selectSingleNode("price").getText());
                        if (e.attributeValue("discount").equals("true")) {

                            double money = buyCount * price * 0.7;
                            System.out.println("消费的金额为：" + money);
                        } else {
                            double money1 = buyCount * price;
                            System.out.println("消费的金额为：" + money1);
                        }
                        e.selectSingleNode("stockcount").setText(String.valueOf((stockcount - buyCount)));

                    } else {
                        System.out.println("库存不够，只能买的数量为：" + stockcount);
                        e.selectSingleNode("stockcount").setText(String.valueOf(0));
                    }
                    flag = false;

                }

            }
            if (flag) {
                System.out.println("输入的商品编号错误，请重新输入");
            }

        } catch (DocumentException e) {
            e.printStackTrace();
        }
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("utf-8");
        try {
            XMLWriter xm = new XMLWriter(new FileWriter("D:\\中国玩家\\products.xml"), format);
            xm.write(document);
            xm.close();
            System.out.println("xie ru chenggong");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
